
let tree = (function () {
    let base = (function () {
        let b = []

        // A-Z
        for (let i = 65; i < 91; i++) {
            b.push(String.fromCharCode(i))
        }
        // a-z
        for (let i = 97; i < 123; i++) {
            b.push(String.fromCharCode(i))
        }
        // 0-9
        for (let i = 0; i < 10; i++) {
            b.push(i.toString())
        }

        return b
    })()

    let Node = function () {}

    let fn = Node.prototype

    // 根据id获取节点
    fn.getNodeById = function (root, id) {
        if (id === root.id) {
            return root
        }
        return fn.forEachNode(root.children, id)
    }

    // 深度优先遍历
    fn.forEachNode = function (nodes, id) {
        if (nodes) {
            for (let i = 0; i < nodes.length; i++) {
                let each = nodes[i]
                if (id === each.id) {
                    return each
                } else {
                    let res = fn.forEachNode(each.children, id)
                    if (res) {
                       return res
                    }
                }
            }
        } else {
            return undefined
        }
    }

    // 遍历获取节点数
    fn.getConut = function (node) {
        // ROOT
        let sum = 1

        sum += fn.getChildrenConut(node)
        return sum
    }

    fn.getChildrenConut = function (node) {
        // 增加层级数
        let sum = 1
        let children = node.children

        if (children && Array.isArray(children) && (children.length > 0)) {
            sum = children.length

            children.forEach(v => {
                let num = fn.getChildrenConut(v)
                sum += num
            })

            return sum
        } else {
            return 0
        }
    }

    fn.UUID = function (num) {
        let result = new Array(num)

        let size = base.length

        let index = 0

        for (let i = 0; i < num; i++) {
            index = Math.floor(Math.random() * size)
            result[i] = base[index]
        }

        return result.join('')
    }

    console.log('tree init!')

    return new Node()
})()

export default tree
